var Game = require('Game');
cc.Class({
    extends: cc.Component,

    properties: {
        roundLeb:cc.Label,
        gamesLeb:cc.Label,
        
        bigTotalLab:cc.Label,
        bigSelfLab:cc.Label,
        bigSelect:cc.Sprite,
        bigPeopleLab:cc.Label,
        bigSelectLight:cc.Node,

        smallTotalLab: cc.Label,
        smallSelfLab: cc.Label,
        smallSelect: cc.Sprite,
        smallPeopleLab:cc.Label,
        smallSelectLight:cc.Node,
       
        gameScoreLeb:cc.Label,
        versionLeb:cc.Label,
        flagBig:cc.Node,
        flagSmall:cc.Node,

        bigTotal:0,
        bigSelf:0,
        bigPeople:0,
        

        smallTotal:0,
        smallSelf:0,
        smallPeople:0,
        
        //游戏携带分数
        gameScore:0,
        //局数
        games:1,
        //本局得分
        winScore:1000,
        //3个骰子点数
        points: {
            default: [],
            type: cc.Integer
        },
        gameList:{
            default: [],
            type: cc.Integer
        },


        gameTimes:30,
       
    
        
        spriteFrame: {
            default: [],
            type: cc.spriteFrame
        }, 
        spriteFrameSamll: {
            default: [],
            type: cc.spriteFrame
        }, 

        
        // 平衡节点
        inBalance:cc.Node,
        inBalanceLab:cc.Label,

        listFlag: {
            default: [],
            type: cc.spriteFrame
        }, 
        listFlagSprite: {
            default: [],
            type: cc.Sprite
        }, 

    },

    // LIFE-CYCLE CALLBACKS:



     onLoad () {
        cc.resources.load("atlas/v2game", cc.SpriteAtlas, (err, atlas) => {
            this.spriteFrame[0] = atlas.getSpriteFrame('btn_big_1');
            this.spriteFrame[1] = atlas.getSpriteFrame('btn_big_2');
            this.spriteFrame[2] = atlas.getSpriteFrame('btn_big_3');
            this.spriteFrameSamll[0] = atlas.getSpriteFrame('btn_small_1');
            this.spriteFrameSamll[1] = atlas.getSpriteFrame('btn_small_2');
            this.spriteFrameSamll[2] = atlas.getSpriteFrame('btn_small_3');
            this.loadOver=true
          
            
        })
       
        cc.resources.load("atlas/v2game", cc.SpriteAtlas, (err, atlas) => {
               // this.listFlag[0] = atlas.getSpriteFrame('icon_');
                this.listFlag[1] = atlas.getSpriteFrame('icon_blue');
                this.listFlag[2] = atlas.getSpriteFrame('icon_red');    
            })

          

        this.scalGameList(this.listFlagSprite[0].node);
        this.gameScoreLeb.string=this.num1000(this.gameScore);
        this.gamesLeb.string=this.num1000(this.games);
        //this. versionLeb.string='Release-V1.0.9';
        this. versionLeb.string='Test-V2.0.2';

        this.roundLeb.string=Game.instance.LL.t('label.PreviousRound');
        this.inBalanceLab.string=Game.instance.LL.t('label.InBalance');
        this.Betting=Game.instance.LL.t('label.Betting');

       
     },

   


     reset(){
    
       this.bigSelf=0;
       this.smallSelf=0;

       this.bigSelfLab.string=this.bigSelf;
       this.smallSelfLab.string=this.smallSelf;

    

       this.bigSelect.spriteFrame=this.spriteFrame[0];
       this.smallSelect.spriteFrame=this.spriteFrameSamll[0];

       this.gameTotal(0,0); 
       
     },

    newGame(){
       
        this.reset();
    },

    gameRoomInfo(cmd){
        var obj = cmd;
       // cc.log('GameKernel=='+obj.toString());
        //更新数据
        this.gameTimes=obj.gameTimes;
        if (this.gameTimes>0) {
           // cc.log('GameKernel==hide');
            Game.instance.gameStartHide();
        }
        if (this.gameTimes<=5&&this.gameTimes>0) {
            this.inBalance.active=true;
         }else{
            this.inBalance.active=false;
         }
          if(this.gameTimes==1) {
            setTimeout(() => {
                // 延时1秒后执行的代码
                this.inBalance.active=false;
              }, 500);

           
         }
       
        this.bigPeople=obj.bigPeople;
        this.bigTotal=obj.bigTotal;

        this.smallPeople=obj.smallPeople;
        this.smallTotal=obj.smallTotal;

        this.games=obj.games;
      
        this.gameList=obj.gameList;
        this.gameLsitWirte();

        //设置Leb数据
        this.gamesLeb.string=this.num1000(this.games);
         
        this.bigPeopleLab.string= this.num1000(this.bigPeople) ;
        this.bigTotalLab.string=this.num1000(this.bigTotal) ;

        this.smallPeopleLab.string=this.num1000(this.smallPeople) ;
        this.smallTotalLab.string=this.num1000(this.smallTotal) ;

        this.gameScoreLeb.string=this.num1000(this.gameScore) ;
        this.gamesLeb.string=this.num1000(this.games) ;

       //服务器数据驱动=============================================
        Game.instance.gameStart();
       // 更新文本标签显示的倒计时时间
       
        Game.instance.gameCountdown(this.gameTimes);


    },

    gameResult(cmd){

        this.points=cmd.points;
        this.bigWinScore=cmd.bigWinScore;
        this.smallWinScore=cmd.smallWinScore;

        //服务器数据驱动=============================================
        Game.instance.gameOpenJiangAnima();
        setTimeout(() => {
            // 延时1秒后执行的代码
            Game.instance.gameOpenJiangResult();
          }, 2000);

          setTimeout(() => {
            // 延时1秒后执行的代码
            Game.instance.gameOpenJiangResult2();
          }, 3000);

    },

    userInfoUpdate(cmd){
        this.gameScore=cmd.score;
        this.bigBetScoreTotal=cmd.bigBetScoreTotal-cmd.returnBigBetScore;
        this.smallBetScoreTotal=cmd.smallBetScoreTotal-cmd.returnSmallBetScore;
        this.user=cmd;
        this.selectFlag=cmd.selectFlag;

       
        //选择返回
        
        this.joinNewLive=this.user.status==2?true:false;

        
        if (this.joinNewLive) {
            let str=  Game.instance.LL.t('label.tips6')
            Game.instance.mToast.show(str,5);
            this.bigSelfLab.string=this.Betting;
            this.smallSelfLab.string=this.Betting;
        
            return 
        }

      if ( this.loadOver) {

        this.big=cmd.selectBig==1;
        this.bigSelect.spriteFrame=this.big?this.spriteFrame[2]:this.spriteFrame[0];
       // cc.log('选择返回大...'+this.big);
        
        this.small=cmd.selectSmall==1;
        this.smallSelect.spriteFrame=this.small?this.spriteFrameSamll[2]:this.spriteFrameSamll[0];
       // cc.log('选择返回小...'+this.small);

      //  cc.log('选择返回...'+this.selectFlag);
        this.bigSelectLight.active=(this.selectFlag==1);
        
        this.smallSelectLight.active=(this.selectFlag==2);
    }
        
        //
        let tSmall=cmd.returnSmallBetScore;
        if (tSmall>0) {//如果小有退分
            
        this.smallSelf=cmd.smallBetScoreTotal;
        let t=Math.floor(tSmall/20);
        let count = 0;
        const intervalId = setInterval(() => {
        this.smallSelf-=t;
         if (this.smallSelf<=this.smallBetScoreTotal) {
            this.smallSelf=this.smallBetScoreTotal;
            clearInterval(intervalId);
            cc.log('定时任务执行完');
        } 
       
        cc.log('定时任务执行中...'+this.smallSelf);
        this.smallSelfLab.string = this.num1000(this.smallSelf);
        Game.instance.audioMng.playChips();

        count++;

        }, 100); 

        }else{
                
        this.smallSelfLab.string =this.num1000(this.smallBetScoreTotal);
        }

        //
        let tBig=cmd.returnBigBetScore;
        if (tBig>0) {//如果有退分
            
        this.bigSelf=cmd.bigBetScoreTotal;
        let t=Math.floor(tBig/20);

        let count = 0;
        const intervalId = setInterval(() => {
            this.bigSelf-=t;
        if (this.bigSelf<=this.bigBetScoreTotal) {
            this.bigSelf=this.bigBetScoreTotal;
            clearInterval(intervalId);
            cc.log('定时任务执行完');
        } 
        cc.log('定时任务执行中...'+this.bigSelf);
        this.bigSelfLab.string = this.num1000(this.bigSelf);
        Game.instance.audioMng.playChips();
        count++;

        }, 100); 

        }else{
            this.bigSelfLab.string = this.num1000(this.bigBetScoreTotal);
        }
        
       
        
        
        // this.showSelectBtn();

        // setTimeout(() => {
        //   // 延时1秒后执行的代码
        //   this.showSelectBtn();
        // }, 500);
    },

 

    gameStart(){
       //服务器数据驱动=============================================
       Game.instance.gameReset();
       cc.log('gameStart');
       this.selectFlag=0;
    },

    addStake:function(selectFlag,score) {
        
        if (this.joinNewLive) {
            cc.log('进入新直播间，本局不能押注');
            let str=  Game.instance.LL.t('label.tips6')
            Game.instance.mToast.show(str,3);
            return;
        }
        if (this.gameTimes<=5) {
            cc.log('平衡中，不能投注');
            let str=  Game.instance.LL.t('label.tips2')
            Game.instance.mToast.show(str,3);
            return;
        } 

        if(selectFlag==0){
            cc.log('请先选择 大 或者 小 ');
            let str=  Game.instance.LL.t('label.tips1')
            Game.instance.mToast.show(str,3);
            return;
        }
        if (score>this.gameScore) {
            cc.log('分数不足');
            let str=  Game.instance.LL.t('label.tips3')
            Game.instance.mToast.show(str,3);
            return;
        } 
        
        
        if (selectFlag==0) {//说明是分数按钮进来的
            selectFlag=this.selectFlag;
        }
       
        if(selectFlag==1){
           
            this.bigSelf+=score;
            this.bigSelfLab.string = this.num1000(this.betScoreTotal);
    
        }

        if(selectFlag==2){
           
            this.smallSelf+=score;
            this.smallSelfLab.string =this.num1000(this.betScoreTotal) ;
        }

        
        let bigBet=0;
        let smallBet=0;
        let clearBet=0;

        if(selectFlag==1){
           
            bigBet=score;
            this.bigSelfLab.string = this.num1000(this.bigBetScoreTotal);
    
        }

        if(selectFlag==2){
           
            smallBet=score;
            this.smallSelfLab.string =this.num1000(this.smallBetScoreTotal) ;
        }

        //更新自己分数
        {
            this.gameScore-=score;
            this.gameScoreLeb.string=this.num1000(this.gameScore) ;
          
        let cmd= {
            uid:this.user.id,
            bigBetScore:bigBet,
            smallBetScore:smallBet,
            clearBet:clearBet,
            }
          
             this.webSend(200,101,cmd);
                
        }
        
     },

     
     login(){
        let cmd={
            uid:Game.instance.userId,
            token:Game.instance.token,
            liveid:Game.instance.liveid,
            stream:Game.instance.stream,

        }
        cc.log('200-100:'+Game.instance.userId);

        this.webSend(200,100,cmd);
     },
     heart(){
        let cmd={
            uid:Game.instance.userId,
        }
        cc.log('0-0:'+Game.instance.userId);

        this.webSend(0,0,cmd);
     },
     getScore(){
        let cmd={
            uid:Game.instance.userId,
            token:Game.instance.token,
        }
        cc.log('200-103:'+Game.instance.userId);

        this.webSend(200,103,cmd);
     },

     webSend(main,sub,cmd){
     //发送押注分数给服务器
      let message = {
        main: main,
        sub: sub,
        cmd: cmd
       };
      let msg = JSON.stringify(message);

        Game.instance.ws.sendMessage(msg);
     },



     gameTotal:function(big,small){
        this.bigTotal=big;
        this.smallTotal=small;
        this.bigTotalLab.string = big;
        this.smallTotalLab.string = small;

     },
    
     
     
     selectBig:function(){
        //TODO 修改为发送选择给服务器，服务器返回后确认选大，选小；
        if (this.joinNewLive) {
            let str=  Game.instance.LL.t('label.tips6')
            Game.instance.mToast.show(str,5);
            return 
        }
       
       

        if (this.big) {
            //清除
            this.sendBet(0,0,1,0,0);   
           
            Game.instance.audioMng.playReturnBet(); 
                 
        } else{
            //选择大
           
            this.sendBet(0,0,0,1,0); 
        }
        
     },
     selectSmall:function(){
        if (this.joinNewLive) {
            let str=  Game.instance.LL.t('label.tips6')
            Game.instance.mToast.show(str,5);
            return 
        }
        
        if (this.small) {
            //清除
            this.sendBet(0,0,2,0,0);    
            Game.instance.audioMng.playReturnBet();       
        } else{
            //选择小
           
            this.sendBet(0,0,0,0,1); 
        }
     },

     sendBet(big,small,clear,sBig,sSmall){
        let cmd= {
            uid:this.user.id,
            bigBetScore:big,
            smallBetScore:small,
            clearBet:clear,
            selectBig:sBig,
            selectSmall:sSmall
            }
          
            this.webSend(200,101,cmd);
     },



     showSelectBtn(){


        
        if (this.bigBetScoreTotal>0) {
            this.bigSelect.spriteFrame=this.spriteFrame[2];
        }else{
            this.bigSelect.spriteFrame=this.spriteFrame[0];
        }

        if (this.smallBetScoreTotal>0) {
            this.smallSelect.spriteFrame=this.spriteFrameSamll[2]; 
        }else{
            this.smallSelect.spriteFrame=this.spriteFrameSamll[0]; 
        }
        

 },


      hideAllChildren:function(node) {
        node.eachChild(function (child) {
            child.visible = false;
            // 递归隐藏子节点的子节点
            hideAllChildren(child);
        });
    },
     
     num1000:function(num) {
        if (num>=1000*1000*1000) {
            let n=Math.floor(num/1000/1000);
            return this.num1000(n)+'M'; 
        }
        if (num>=1000000) {
            let n=Math.floor(num/1000);

            return this.num1000(n)+'k'; 
        }
       
     return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
       
    },
    num1000d2:function(num) {
        
        var numStr = num.toFixed(2).toString();
        // 使用正则表达式添加千位分隔符
        var parts = numStr.split(".");
        parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        return parts.join(".");
       
    },


    scal(flag){
        // 获取当前节点
     var node;
     if (flag>10) {
        node= this.flagBig; 
        cc.log('===scal -big');
     } else {
        node= this.flagSmall; 
        cc.log('===scal -small');
     }
 
     // 创建缩放动画动作
     var scaleTo1 = cc.scaleTo(0.6, 1.4);
     var scaleTo05 = cc.scaleTo(0.6, 1.0);
 
     // 将动画动作组合成序列
     var sequence = cc.sequence(scaleTo1, scaleTo05).clone();
 
     // 将序列动作无限循环
     //var repeat = cc.repeatForever(sequence);

     var repeat = cc.repeat(sequence, 3);
 
     // 运行动画
     node.runAction(repeat);
    },

    scalDJS(node){
     // 创建缩放动画动作
     var scaleTo1 = cc.scaleTo(0.4, 1.3);
     var scaleTo05 = cc.scaleTo(0.6, 1.0);
     // 将动画动作组合成序列
     var sequence = cc.sequence(scaleTo1, scaleTo05).clone();
 
     var repeat = cc.repeat(sequence, 1);
     // 运行动画
     node.runAction(repeat);
    },

    
    scalGameList(node){
        // 创建缩放动画动作
        var scaleTo1 = cc.scaleTo(0.4, 1.3);
        var scaleTo05 = cc.scaleTo(0.6, 1.0);
        // 将动画动作组合成序列
        var sequence = cc.sequence(scaleTo1, scaleTo05).clone();
    
        var repeat = cc.repeatForever(sequence);
        // 运行动画
        node.runAction(repeat);
       },

    gameLsitWirte(){
        { 
        var array=  this.listFlagSprite;
    for (let index = 0; index < array.length; index++) {
        const element = array[index];
        const total= this.gameList[index]
        if (total>10) {
            element.spriteFrame=this.listFlag[1];   
        }else if (total>=3&&total<=10){
            element.spriteFrame=this.listFlag[2];  
        }else{
            element.spriteFrame=this.listFlag[0];  
        }
      
    }
    
}}
   
    
    
     
});
